<template>
  <div class="main">
    <el-card class="box-card main">
      <template #header>
        <div class="card-header">
          <div class="alitem">
            <el-icon @click="onClickBack">
              <ArrowLeftBold />
            </el-icon>
            <span>志愿表详情</span>
            <div class="userInfo" style="margin-left: 10px">
              <span>{{ userInfo.nick }}</span>
              <span>{{ userInfo.sex == '1' ? '女' : '男' }}</span>
              <span> {{ userInfo.province }}</span>
              <span>{{ zyInfo.score }}分</span>
              <span>{{ zyInfo.section > 0 ? zyInfo.section + '位' : '' }}</span>
              <span>{{ zyInfo.sgname }}</span>
              <span>{{ zyInfo.batch }}</span>
            </div>
          </div>
        </div>
      </template>
      <el-row :gutter="20" justify="space-between">
        <el-col :span="8">
          <div class="alitem">
            <el-icon :size="20" v-if="status > 0">
              <Edit @click="dialogFormVisible = true" />
            </el-icon>
            <div style="margin: 0 10px; font-weight: bold">
              {{ zyInfo.title }}
            </div>
            <div style="font-size: 14px">
              数据更新时间: {{ zyInfo.lastModificationTime }}
            </div>
          </div>
        </el-col>
        <el-col :span="14" v-if="status > 0">
          <div class="curr df" style="font-size: 15px">
            <div
              v-if="routeData.isZhuanjia != 2"
              class="df"
              style="margin: 0 20px 0 0"
            >
              <div>同步至老师</div>
              <div>
                <el-switch
                  v-model="zyInfo.isTeacherSee"
                  @change="zyInfoChange"
                />
              </div>
            </div>
            <div class="df">
              <div
                class="alitem"
                :class="currentSort == 'chance' ? 'sortSel' : ''"
                @click="sortHandleCommand('chance')"
              >
                <img
                  v-if="currentSort == 'chance'"
                  class="sortImg"
                  src="../../assets/images/sort_1_s.png"
                />
                <img
                  v-else
                  class="sortImg"
                  src="../../assets/images/sort_1_n.png"
                />
                &nbsp;录取概率
              </div>
              <div
                class="alitem"
                :class="currentSort == 'rank' ? 'sortSel' : ''"
                style="margin: 0 20px"
                @click="sortHandleCommand('rank')"
              >
                <img
                  v-if="currentSort == 'rank'"
                  class="sortImg"
                  src="../../assets/images/sort_2_s.png"
                />
                <img
                  v-else
                  class="sortImg"
                  src="../../assets/images/sort_2_n.png"
                />
                &nbsp;院校排名
              </div>
              <div
                class="alitem"
                :class="currentSort == 'position' ? 'sortSel' : ''"
                @click="sortHandleCommand('position')"
              >
                <img
                  v-if="currentSort == 'position'"
                  class="sortImg"
                  src="../../assets/images/sort_2_s.png"
                />
                <img
                  v-else
                  class="sortImg"
                  src="../../assets/images/sort_2_n.png"
                />
                &nbsp;位次排序
              </div>
              <div style="margin: 0 20px" @click="onClickUpdate">修改</div>
              <div
                @click="onClickSave"
                :style="
                  isInitialLoad ? 'color:red;border-bottom:2px solid red;' : ''
                "
              >
                保存
              </div>
              <div style="margin: 0 20px" @click="onClickDownload">下载</div>
              <div
                @mouseover="onMouseoverShare"
                @mouseout="isShowQrImage = false"
              >
                分享
              </div>
            </div>
          </div>
          <div v-show="isShowQrImage" class="qr-box" v-loading="loading">
            <img style="width: 100%; height: 100%" :src="shareQrImage" />
          </div>
        </el-col>
      </el-row>
      <div v-if="zy_type == 1" class="classifyheader margintop">
        <div class="flex sizebg">
          <div style="margin-left: 10px" class="alitem">排序</div>
          <div style="margin-left: 20px" class="alitem">录取概率</div>
          <div style="margin-left: 20px" class="alitem">专业</div>
          <div style="margin-left: 120px" class="alitem">院校</div>
        </div>
        <div class="flex sizeinfo">
          <div class="alitem">{{ zyInfo.today_year }}招生计划</div>
          <div style="width: 110px" class="center">历年</div>
          <div style="width: 110px" class="center">
            {{ zyInfo.today_year - 1 }}
          </div>
          <div style="width: 110px" class="center">
            {{ zyInfo.today_year - 2 }}
          </div>
          <div style="width: 110px" class="center">
            {{ zyInfo.today_year - 3 }}
          </div>
          <div style="margin-left: 60px; margin-right: 0px">操作</div>
        </div>
      </div>
      <div v-else class="classifyheader margintop">
        <div class="flex sizebg">
          <div style="margin-left: 10px" class="alitem">排序</div>
          <div style="margin-left: 20px" class="alitem">录取概率</div>
          <div style="margin-left: 44px" class="alitem">院校</div>
        </div>
        <div class="flex sizeinfo">
          <div class="alitem" style="margin-right: 10px">
            {{ zyInfo.today_year }}招生计划
          </div>
          <div style="width: 110px" class="center">历年</div>
          <div style="width: 110px" class="center">
            {{ zyInfo.history_year - 0 }}
          </div>
          <div style="width: 110px" class="center">
            {{ zyInfo.history_year - 1 }}
          </div>
          <div style="width: 110px" class="center">
            {{ zyInfo.history_year - 2 }}
          </div>
          <div style="margin-left: 30px; margin-right: 14px">操作</div>
        </div>
      </div>
      <sdVolunteerlist
        v-if="zy_type == 1"
        :batchs="batchs"
        :sortNum="sortNum"
        :isZhuanjia="routeData"
        :status="status"
        style="margin-top: 10px"
        @changeSdInitialLoad="changeSdInitialLoad"
      />
      <jsVolunteerlist
        v-else-if="zy_type == 2"
        :batchs="batchs"
        :sortNum="sortNum"
        :isZhuanjia="routeData"
        :status="status"
        style="margin-top: 10px"
        @changeInitialLoad="changeInitialLoad"
      />
      <scVolunteerlist
        v-else
        :batchs="batchs"
        :sortNum="sortNum"
        :isZhuanjia="routeData"
        :status="status"
        style="margin-top: 10px"
        @changeScInitialLoad="changeScInitialLoad"
      />
    </el-card>
  </div>

  <el-dialog v-model="dialogFormVisible" title="志愿表命名" width="500">
    <el-form>
      <el-form-item label="志愿表名称" :label-width="formLabelWidth">
        <el-input
          v-model="volunteerTitle"
          autocomplete="off"
          placeholder="请输入志愿表名称"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="onClickUpdateTitle"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
// import userInfoDialog from '@/views/leader/volunteer/module/userInfoDialog.vue'
import jsVolunteerlist from './components/jsVolunteerlist.vue';
import scVolunteerlist from './components/scVolunteerlist.vue';
import sdVolunteerlist from './components/sdVolunteerlist.vue';
import { useRoute, useRouter } from 'vue-router';
import { getZyInfo, zySave, shareZY } from '@/api/volunteer/volunteer';
import { useStore } from 'vuex';
import { ref, onBeforeMount } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import QRCode from 'qrcode';
// 获取等效位差的公共方法
import { calculateEquivalents } from '@/utils/batchEquivalents.js';

// 路由信息
const router = useRouter();
// 路由信息
const route = useRoute();
// 仓库
const store = useStore();

const batchs = ref([]);
const zyInfo = ref({}); // 志愿详情信息
const volunteerInfos = ref([]); // 志愿表信息
const tempVolunteerInfos = ref([]); // 志愿表信息
const index = ref(''); // 志愿表的index
const zy_type = ref(''); // 志愿表类型 1-山东 2-江苏 3-四川
const status = ref(0); // 志愿表状态 0-已过期， 1-未过期
const userInfo = store.getters.user.userInfo; // 学生数据
const dialogFormVisible = ref(false); // 是否显示修改志愿表名称弹窗
const volunteerTitle = ref(''); // 志愿表标题
const currentSort = ref(''); // 当前排序
const sortNum = ref(0); // 当前排序
const routeData = ref({});
const isShowQrImage = ref(false); // 是否显示分享二维码
const shareUrl = ref(null); // 分享地址
const shareQrImage = ref(null); // 分享二维码图片
const loading = ref(false);
const batchEqus = ref({});

const isInitialLoad = ref(false);

onBeforeMount(() => {
  store.dispatch('tianbao/setVolunteerInfos', []);
});
init();

const changeSdInitialLoad = (sdIsInitial) => {
  isInitialLoad.value = sdIsInitial;
};
const changeScInitialLoad = (scIsInitial) => {
  isInitialLoad.value = scIsInitial;
};
const changeInitialLoad = (scIsInitial) => {
  isInitialLoad.value = scIsInitial;
};

function init() {
  let data = JSON.parse(route.query.data);
  index.value = data.index;
  zy_type.value = data.zy_type;
  status.value = data.status;

  getVolunteerInfo();
}

function onClickBack() {
  router.back();
}

// 获取志愿表信息
function getVolunteerInfo() {
  getZyInfo({ index: index.value }).then((res) => {
    localStorage.setItem('course', res.data.data.course || '');
    status.value = res.data.data.status;
    batchs.value = res.data.data.batchs;
    zyInfo.value = res.data.data;
    zyInfo.value.isTeacherSee = !!zyInfo.value.isTeacherSee;

    const volunteer = zyInfo.value.volunteerInfos;
    var volunteerInfosData = [];
    // 判断是否为array类型，否则为历史老数据object类型，兼容为array类型
    if (!Array.isArray(volunteer)) {
      for (let key in volunteer) {
        let info = volunteer[key].collegeData;
        info.majorsInfo = volunteer[key].majorsInfo;
        info.vkey = key;

        volunteerInfosData.push(info);
      }
    } else {
      volunteerInfosData = volunteer;
    }
    batchEqus.value = res.data.data.batchEqus;

    // 获取等效位差的公共方法
    volunteerInfos.value = calculateEquivalents(
      volunteerInfosData,
      batchEqus.value,
    );
    tempVolunteerInfos.value = volunteerInfos.value;
    volunteerTitle.value = zyInfo.value.title;

    store.dispatch('tianbao/setVolunteerInfos', volunteerInfos.value);
  });
}

function getDownloadUrl(isDownLoad) {
  let data = { index: index.value, fronttype: 3 };

  shareZY(data)
    .then((res) => {
      loading.value = false;
      shareUrl.value = res.data.data.url;
      // 生成二维码
      generateQR(shareUrl.value).then((res) => {
        shareQrImage.value = res;
      });

      if (isDownLoad) {
        window.location.href = shareUrl.value;
        ElMessage.success('下载成功');
      }
    })
    .catch(() => {
      shareUrl.value = null;
    });
}

const generateQR = async (text) => {
  try {
    const opts = {
      errorCorrectionLevel: 'H',
      type: 'image/png',
      quality: 0.9,
      margin: 1,
    };
    const qrImage = await QRCode.toDataURL(text, opts);
    return qrImage;
  } catch (err) {
    console.log('err:', err);
  }
};

// 修改志愿表是否同步至学生
function zyInfoChange() {
  let data = {};
  data['isTeacherSee'] = zyInfo.value.isTeacherSee ? 1 : 0;
  updateZyInfo(data);
}

// 排序
function sortHandleCommand(type) {
  if (zy_type.value == 3) {
    volunteerInfos.value = store.getters.tianbao.volunteerInfos;
  }
  currentSort.value = type;
  switch (type) {
    case 'chance':
      chanceSort();
      break;
    case 'rank':
      rankSort();
      break;
    case 'position':
      positionSort();
  }
  sortNum.value += 1;
}

// 志愿表排序
function volunteerInfosSort(sortKey) {
  volunteerInfos.value = volunteerInfos.value
    .slice()
    .sort((a, b) => a[sortKey] - b[sortKey]);

  store.dispatch('tianbao/setVolunteerInfos', volunteerInfos.value);
}

// 录取率排序
function chanceSort() {
  volunteerInfosSort('chance');
}

// 院校排名排序
function rankSort() {
  volunteerInfosSort('rank');
}

// 位次排序
function positionSort() {
  volunteerInfosSort('minRank');
}

// 点击保存志愿表
function onClickSave() {
  shareUrl.value = null;

  let data = {};
  data['volunteerInfos'] = JSON.stringify(store.getters.tianbao.volunteerInfos);

  updateZyInfo(data);
}

// 点击下载
function onClickDownload() {
  if (shareUrl.value != null) {
    window.location.href = shareUrl.value;
    ElMessage.success('下载成功');
  } else {
    getDownloadUrl(true);
  }
}

function onMouseoverShare() {
  isShowQrImage.value = true;

  if (shareUrl.value == null) {
    loading.value = true;
    getDownloadUrl();
  }
}

// 点击修改志愿表
function onClickUpdate() {
  // if (routeData.value.isZhuanjia == 2) {
  // ElMessage.error("专家填报志愿无法操作");
  // } else {

  if (isInitialLoad.value) {
    ElMessageBox.confirm(
      '当前志愿表信息有修改尚未保存，是否放弃更改并离开当前页面？',
      '提示',
      { confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning' },
    ).then(() => {
      store.dispatch('tianbao/setVolunteerInfos', tempVolunteerInfos.value);
      gotoUpdateVolunteer();
    });
  } else {
    gotoUpdateVolunteer();
  }
}

function gotoUpdateVolunteer() {
  console.log('zyInfo.value:', zyInfo.value);
  let body = {
    update: true,
    batchInfo: {
      batch: zyInfo.value.batch,
      score: zyInfo.value.score,
      section: zyInfo.value.section,
      sgname: zyInfo.value.sgname,
      copyfrom: zyInfo.value.id,
    },
  };
  let jsonStr = JSON.stringify(body);
  router.push({ path: '/volunteer', query: { data: jsonStr } });
}

// 修改志愿表标题
function onClickUpdateTitle() {
  dialogFormVisible.value = false;
  zyInfo.value.title = volunteerTitle.value;

  let data = {};
  data['title'] = volunteerTitle.value;

  updateZyInfo(data);
}

// 更新志愿表信息
function updateZyInfo(data) {
  data['index'] = index.value;
  if (data['volunteerInfos']) {
    tempVolunteerInfos.value = JSON.parse(data['volunteerInfos']);
  }
  zySave(data).then(() => {
    isInitialLoad.value = false;
    // 修改成功
    ElMessage({ message: '更新成功', type: 'success' });
  });
}
routeData.value = JSON.parse(route.query.data);
</script>
<style lang="scss" scoped>
.box-card {
  margin: 20px;
  width: auto;
  height: calc(100vh - 120px);
  overflow-y: auto;

  .tabs {
    color: #000000;
    font-weight: 600;
    cursor: pointer;
  }

  .active {
    color: #004cf7;
    font-weight: 600;
    cursor: pointer;
  }

  .card-header {
    font-size: 20px;
    font-weight: 600;
    color: #1d2129;
    padding: 10px;

    .userInfo {
      margin-left: 30px;
      font-size: 16px;
      font-weight: 400;
      color: #1d2129;
      line-height: 16px;

      span {
        margin-left: 8px;
      }
    }

    .headerSize {
      color: #4e5969;
      font-size: 14px;
      margin-left: 12px;
      font-weight: 400;
      height: 20px;
      line-height: 21px;
    }
  }
}

.classifyheader {
  background: #fafafa;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  color: #86909c;
  letter-spacing: 0;
  line-height: 28px;
  padding-right: 30px;
}

.qr-box {
  position: absolute;
  top: 30px;
  right: 0;
  width: 120px;
  height: 120px;
  border: 1px #efefef solid;
  padding: 5px;
  background-color: white;
  z-index: 999;
  box-shadow: 1px 1px 4px 1px #efefef;
  border-radius: 5px;
}

.sortSel {
  color: #165dff;
}

.sortImg {
  width: 16px;
  height: 16px;
}
</style>
